package com.mo.lib.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import com.mo.lib.utils.KLog
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType

/**
 * @ author：mo
 * @ data：2021/9/23:17:24
 * @ 功能：https://blog.csdn.net/weixin_57207173/article/details/118787293
 */
abstract class BaseVbFragment<VB : ViewDataBinding>() : BaseFragment() {

    protected lateinit var viewBinding: VB
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        initViewBinding()
        return viewBinding.root
    }
    private fun initViewBinding(): View {
        val superclass = javaClass.genericSuperclass
        val aClass = (superclass as ParameterizedType).actualTypeArguments[0] as Class<*>
        try {
            val method: Method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
            viewBinding = method.invoke(null, layoutInflater) as VB
        } catch (e: NoSuchMethodException) {
            KLog.e(e.message!!)
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            KLog.e(e.message!!)
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            KLog.e(e.message!!)
            e.printStackTrace()
        }
        return viewBinding.root
    }
}
